package com.ycg.vue.modules.system.service.impl;

import com.ycg.vue.Entity.HomeImagesEntity;
import com.ycg.vue.Entity.OperationLogEntity;
import com.ycg.vue.Entity.UserEntity;
import com.ycg.vue.Enum.LogEnum;
import com.ycg.vue.Enum.MinIOPathEnum;
import com.ycg.vue.constant.Constant;
import com.ycg.vue.constant.TableNameConstant;
import com.ycg.vue.modules.system.Entity.EmailEntity;
import com.ycg.vue.modules.system.Entity.TypeItemEntity;
import com.ycg.vue.modules.system.mapper.SystemMapper;
import com.ycg.vue.modules.user.mapper.FileMapper;
import com.ycg.vue.result.Result;
import com.ycg.vue.modules.system.service.SystemService;
import com.ycg.vue.utils.EmailUtils;
import com.ycg.vue.utils.JwtUtils;
import com.ycg.vue.utils.MinioUtils;
import com.ycg.vue.utils.UUIDUtils;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @Description
 * @Author jink
 * @Date 2024/2/15 18:19
 */
@Service
public class SystemServiceImpl implements SystemService {

    @Resource
    private SystemMapper systemMapper;

    @Resource
    private MinioUtils minioUtils;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private EmailUtils emailUtils;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result pageHomeImages() {
        return Result.success(systemMapper.homeImageList(HomeImagesEntity.builder().status((short) 1).build()));
    }

    @Override
    public Result upload(MultipartFile file) {
        systemMapper.uploadHomePage(UUIDUtils.getUUID(), minioUtils.upload(file, MinIOPathEnum.PAGE_IMG));
        return Result.success();
    }

    @Override
    public Result homeImageList(HomeImagesEntity homeImages) {
        return Result.success(systemMapper.homeImageList(homeImages));
    }

    @Override
    public Result changeHomeImage(Map<String, String> map) {
        String id = map.get("id");
        String status = map.get("status");
        String collect = map.get("collect");
        if (id == null || id.isEmpty() || status == null || status.isEmpty() || collect == null || collect.isEmpty())
            return Result.error(Constant.IMAGE_STATUS_ERROR);
        HomeImagesEntity homeImages = systemMapper.selectHomePageById(id);
        if (homeImages == null) return Result.error(Constant.IMAGE_NOT_EXIST);
        StringBuilder operation = new StringBuilder();
        if (homeImages.getStatus() != Integer.parseInt(status))
            operation.append(TableNameConstant.HOME_IMAGE_STATUS).append(":").append(homeImages.getStatus()).append("-").append(status);
        if (homeImages.getCollect() != Integer.parseInt(collect))
            operation.append(TableNameConstant.HOME_IMAGE_COLLECT).append(":").append(homeImages.getCollect()).append("-").append(collect);
        systemMapper.insertLog(OperationLogEntity.builder().operation(operation.toString()).type(LogEnum.UPDATE.getName()).success(true).build());
        systemMapper.updateHomePageById(id, status, collect);
        return Result.success();
    }

    @Override
    public Result selectTypeByCode(String code) {
        List<TypeItemEntity> list = systemMapper.selectTypeByCode(code);
        return Result.success(list);
    }

    @Override
    public Result picUpload(MultipartFile file) {
        return Result.success(fileMapper.selectByGroupId(minioUtils.upload(file, MinIOPathEnum.MATERIAL_LIBRARY)));
    }

    @Override
    public Result sendMail(String email) {
        String number = UUIDUtils.getRandomNumber(6);
        EmailEntity emailEntity = EmailEntity.builder().to(email).subject(EmailUtils.CODE).content(number).build();
        try {
            CompletableFuture<Boolean> sent = emailUtils.sent(emailEntity);
            if (sent.get()) {
                redisTemplate.opsForValue().set(email, number, 3600);
            } else {
                return Result.error(Constant.EMAIL_SEND_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(Constant.EMAIL_SEND_ERROR);
        }
        return Result.ok(Constant.EMAIL_SEND_SUCCESS);
    }

    @Override
    public UserEntity selectById(String id) {
        return systemMapper.selectById(id);
    }

    @Override
    public Result checkToken(String finderPrint) {
        Object token = redisTemplate.opsForValue().get(finderPrint);
        if(token!=null){
            Claims claims = JwtUtils.parseJWT(token.toString().trim());
            String id = claims.get("id",String.class);
            UserEntity user = systemMapper.selectById(id);
            Map<String,Object> map = new HashMap<>();
            map.put("identity",user.getIdentity());
            map.put("token",token.toString().trim());
            return Result.success(map);
        }else{
            return Result.error(402,"0");
        }
    }
}
